package com.live.util;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class DesTool {
	private static Cipher cipher;
	private static SecretKey securekey;
	private static final String CRYPT_KEY = "owf%2asdf!@afweppxooz!213";
	
	static {
		try {
			//Cipher：提供加密的类，"AES" 表示加密使用的算法
			cipher = Cipher.getInstance("AES");
			 //SecretKey密码生成器，用于生成一个密钥
			securekey = getKey(CRYPT_KEY);
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static SecretKey getKey(String strKey) {
		try {
			KeyGenerator _generator = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(strKey.getBytes());
			_generator.init(128, secureRandom);
			return _generator.generateKey();
		} catch (Exception e) {
			throw new RuntimeException(" 初始化密钥出现异常 ");
		}
	}
	
	public static String encode(String inputData) {
		try {
			//用密钥初始化此 Cipher，Cipher.ENCRYPT_MODE 加密模式
	        cipher.init(Cipher.ENCRYPT_MODE, securekey);
	        
			byte[] result = cipher.doFinal(inputData.getBytes("utf-8"));
			
			String str = new String(Base64.encode(result, Base64.NO_PADDING+Base64.NO_WRAP+Base64.URL_SAFE));
			
			System.out.println(str);
			
			return str;
			
		} catch (Exception ex) {
			ex.printStackTrace();
		}
       return null;
	}
	
	public static String decode(String inputData) {
		try {
			//解密的时候，要用原来加密的密钥
			cipher.init(Cipher.DECRYPT_MODE, securekey);
			//解密，得到加密前的字符串
			byte[] data = Base64.decode(inputData.getBytes("utf-8"), Base64.NO_PADDING+Base64.NO_WRAP+Base64.URL_SAFE);
			
			byte[] result = cipher.doFinal(data);
			
			String str = new String(result,"utf-8");
			
			System.out.println(str);
			
			return str;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		System.out.println("----------------");
		String pwd = "P@ssword123";
		
		String data = DesTool.encode(pwd);
		
		String dat =	DesTool.decode("Bp2pfrkG9SZCkXXrwLyW_w");
		System.out.println(dat);
	}
}